package com.youwe1.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youwe1.wiki.domain.User;
import com.youwe1.wiki.domain.UserExample;
import com.youwe1.wiki.exception.BusinessException;
import com.youwe1.wiki.exception.BusinessExceptionCode;
import com.youwe1.wiki.mapper.UserMapper;
import com.youwe1.wiki.req.UserLoginReq;
import com.youwe1.wiki.req.UserQueryReq;
import com.youwe1.wiki.req.UserResetPasswordReq;
import com.youwe1.wiki.req.UserSaveReq;
import com.youwe1.wiki.resp.PageResp;
import com.youwe1.wiki.resp.UserLoginResp;
import com.youwe1.wiki.resp.UserQueryResp;
import com.youwe1.wiki.util.CopyUtil;
import com.youwe1.wiki.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<UserQueryResp> list(UserQueryReq req) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        // where 条件 判断name是不是空
        if (!ObjectUtils.isEmpty(req.getLoginName())) {
            criteria.andLoginNameEqualTo(req.getLoginName());
        }

        List<User> userList;
        // 第一页从1开始。而且只会对最近的一条查询方法有效!!!!!
        PageHelper.startPage(req.getPage(), req.getSize());
        // 查询方法
        userList = userMapper.selectByExample(userExample);
        if (req.getPage() > 1 && userList.isEmpty()) {
            // 如果当前页没有数据，页码就减一再次查询
            PageHelper.startPage(req.getPage() - 1, req.getSize());
            userList = userMapper.selectByExample(userExample);
        }
        // 将查询出来的数据处理，去掉无用数据，只返回UserResp里定义的属性
        List<UserQueryResp> list = CopyUtil.copyList(userList, UserQueryResp.class);

        // 生成pageInfo用于获取total
        PageInfo<User> pageInfo = new PageInfo<>(userList);

        // 分页实例
        PageResp<UserQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setPages(pageInfo.getPages());
        pageResp.setPage(req.getPage());
        pageResp.setSize(req.getSize());
        pageResp.setList(list);
        return pageResp;
    }

    public void save(UserSaveReq req) {
        User user = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 判断用户名是否存在
            User userDB = selectByLoginName(req.getLoginName());
            if (ObjectUtils.isEmpty(userDB)) {
                // 新增
                user.setId(snowFlake.nextId());
                userMapper.insert(user);
            } else {
                // 用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        } else {
            // 更新 更新时不修改登录名和密码
            // 设置登录名为null
            user.setLoginName(null);
            // 密码设置为null
            user.setPassword(null);
            // userMapper.updateByPrimaryKey(user);
            // 更新字段时，只有字段有值时才会更新
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    public User selectByLoginName(String LoginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(LoginName);

        List<User> userList = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        }
        return userList.get(0);
    }

    public void resetPassword(UserResetPasswordReq req) {
        User user = CopyUtil.copy(req, User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    public UserLoginResp login(UserLoginReq req) {
        User userDB = selectByLoginName(req.getLoginName());
        if (ObjectUtils.isEmpty(userDB)) {
            // 用户不存在
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        } else {
            // 判断前端传来的密码和数据库密码是否一致（都是两层加密）
            if (userDB.getPassword().equals(req.getPassword())) {
                // 登录成功
                return CopyUtil.copy(userDB, UserLoginResp.class);
            } else {
                // 密码不对
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }
}
